package com.crois.barrier.web.plugin.before;

import com.crois.barrier.common.enums.PluginEnum;
import com.crois.barrier.common.enums.PluginTypeEnum;
import com.crois.barrier.common.exception.BarrierException;
import com.crois.barrier.common.exception.BarrierExceptionEnum;
import com.crois.barrier.plugin.BarrierPlugin;
import com.crois.barrier.plugin.BarrierPluginChain;
import com.crois.barrier.web.support.TokenUtil;
import com.zhimydou.cloud.auth.core.request.AuthAuthentication;
import com.zhimydou.cloud.auth.core.token.service.DefaultTokenServices;
import com.zhimydou.cloud.common.constants.TokenConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Hou Ze Yu
 * @description 请求插件
 * @date 2020/7/13
 */
public class RequestPlugin implements BarrierPlugin {


    private DefaultTokenServices defaultTokenServices;

    public RequestPlugin(DefaultTokenServices defaultTokenServices) {
        this.defaultTokenServices = defaultTokenServices;
    }

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestPlugin.class);

    @Override
    public Mono<Void> execute(ServerWebExchange exchange, BarrierPluginChain chain) {
        LOGGER.info("[开始执行：RequestPlugin]");
        String token = TokenUtil.getToken(exchange.getRequest());
        if (StringUtils.isNotEmpty(token)){
            AuthAuthentication authAuthentication = defaultTokenServices.loadAuthentication(token);
            String userId = authAuthentication.getUserAuthentication().getName();
            LOGGER.info("【授权服务】,token:{}",token);
            LOGGER.info("【授权服务】,userId:{}",userId);
            if (StringUtils.isNotEmpty(token) && StringUtils.isNotEmpty(userId)) {
                // 解析 userId 和 转换 token
                return chain.execute(wrapHeader(exchange,userId,token));
            } else {
                throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_SIGN_IS_NOT_PASS);
            }
        }else {
            return chain.execute(exchange);
        }
    }

    /**
     * 包装request header
     * @param serverWebExchange
     * @param userId
     * @param token
     * @return
     */
    private ServerWebExchange wrapHeader(ServerWebExchange serverWebExchange, String userId,String token) {
        //向headers中放文件，记得build
        ServerHttpRequest request = serverWebExchange.getRequest().mutate()
                .header(TokenConstants.CURRENT_USER_ID_HEADER,userId)
                .header(TokenConstants.TOKEN_HEADER,token)
                .build();
        //将现在的request 变成 change对象
        return serverWebExchange.mutate().request(request).build();
    }

    @Override
    public PluginTypeEnum pluginType() {
        return PluginTypeEnum.BEFORE;
    }

    @Override
    public String name() {
        return PluginEnum.REQUEST.getName();
    }

    @Override
    public int order() {
        return PluginEnum.REQUEST.getCode();
    }

    @Override
    public Boolean skip(ServerWebExchange exchange) {
        return false;
    }
}
